package com.mcflies.activity.welcome;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.mcflies.bean.GridViewBean;
import com.mcflies.commons.CommonsUtil;
import com.mcflies.commons.GridViewBaseAdapter;
import com.mcflies.commons.McfliesConstant;

import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.Toast;

/**
 * @author:mcfly_jun
 * @create_date:2012-8-31
 * @comment:欢迎界面,采用GridView布局
 */
public class WelcomeActivity extends Activity implements OnItemClickListener {
	private GridView gridViewMain_GV;
	private List<GridViewBean> beanList = new ArrayList<GridViewBean>();
	private String[] welcomeMenuArray;
	private AssetManager assetManager;
	private GridViewBaseAdapter gridViewAdapter;

	// ************************************再按一次退出*****************************************//
	private boolean isExit = false;
	private Timer timer = new Timer();
	private MyTimerTask task;

	class MyTimerTask extends TimerTask {
		@Override
		public void run() {
			isExit = false;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			if (isExit) {
				this.finish();
				System.exit(0);
			} else {
				Toast.makeText(this, "再按一次退出...", Toast.LENGTH_SHORT).show();
				isExit = true;
				if (task != null) {
					task.cancel();
				}
				task = new MyTimerTask();// 新建一个任务
				timer.schedule(task, 2000);
			}
			break;
		}
		return false;
	}

	// ************************************再按一次退出*****************************************//

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.gridview_main);
		initData();
		initWidget();
		gridViewMain_GV.setAdapter(gridViewAdapter);
		gridViewMain_GV.setOnItemClickListener(this);
	}

	private void initWidget() {
		gridViewMain_GV = (GridView) findViewById(R.id.gridViewMain_GV);
	}

	private void initData() {
		welcomeMenuArray = getResources().getStringArray(
				R.array.welcomeMenuArray);
		assetManager = getAssets();
		beanList = CommonsUtil.getGridViewData(welcomeMenuArray, assetManager,
				"welcome");
		gridViewAdapter = new GridViewBaseAdapter(this, beanList);
	}

	@Override
	public void onItemClick(AdapterView<?> adapter, View view, int position,
			long id) {
		try {
			Intent intent = new Intent(WelcomeActivity.this,
					Class.forName(beanList.get(position).getIntent()));
			startActivity(intent);
		} catch (Exception e) {
			Log.i(McfliesConstant.MCFLIES_EXCEPTION_INFO_FLAG, e.getMessage());
		}
	}
}